package com.example.myapplication.ui

import android.content.Context
import android.media.MediaPlayer
import android.net.Uri
import androidx.camera.core.*
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.myapplication.viewmodel.ObjectDetectViewModel
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.objects.ObjectDetection
import com.google.mlkit.vision.objects.defaults.ObjectDetectorOptions
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.MediaItem
import java.util.concurrent.Executors
import android.widget.Toast
import android.Manifest
import android.content.pm.PackageManager
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.ui.Alignment
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

@Composable
fun ObjectDetectScreen() {
    val context = LocalContext.current
    val viewModel: ObjectDetectViewModel = viewModel()
    val coroutineScope = rememberCoroutineScope()
    var permissionGranted by remember { mutableStateOf(false) }
    var detectedLabels by remember { mutableStateOf(listOf<String>()) }
    val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
        permissionGranted = granted
        if (!granted) {
            Toast.makeText(context, "请授予摄像头权限以使用物体识别功能", Toast.LENGTH_LONG).show()
        }
    }

    LaunchedEffect(Unit) {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            launcher.launch(Manifest.permission.CAMERA)
        } else {
            permissionGranted = true
        }
    }

    if (permissionGranted) {
        Box {
            CameraPreview(onLabelsDetected = { labels ->
                detectedLabels = labels
            })
            Column(
                modifier = Modifier
                    .align(Alignment.BottomCenter)
                    .fillMaxWidth()
                    .background(Color.White)
                    .padding(16.dp)
            ) {
                Text(text = "检测到的标签：", color = Color.Black)
                detectedLabels.forEach { label ->
                    Text(text = label, color = Color.Black)
                }
            }
        }
    }
}

@Composable
fun CameraPreview(onLabelsDetected: (List<String>) -> Unit) {
    val context = LocalContext.current
    val lifecycleOwner = LocalLifecycleOwner.current
    AndroidView(factory = { ctx ->
        val previewView = PreviewView(ctx)
        val cameraProviderFuture = ProcessCameraProvider.getInstance(ctx)
        cameraProviderFuture.addListener({
            val cameraProvider = cameraProviderFuture.get()
            val preview = Preview.Builder().build().also {
                it.setSurfaceProvider(previewView.surfaceProvider)
            }
            val imageAnalyzer = ImageAnalysis.Builder().build().also {
                it.setAnalyzer(Executors.newSingleThreadExecutor(), { imageProxy ->
                    val mediaImage = imageProxy.image
                    if (mediaImage != null) {
                        val inputImage = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees)
                        val detector = ObjectDetection.getClient(
                            ObjectDetectorOptions.Builder()
                                .setDetectorMode(ObjectDetectorOptions.STREAM_MODE)
                                .enableMultipleObjects()
                                .enableClassification()
                                .build()
                        )
                        detector.process(inputImage)
                            .addOnSuccessListener { results ->
                                val labels = results.flatMap { obj ->
                                    obj.labels.map { label ->
                                        val name = label.text ?: "未知"
                                        val confidence = label.confidence
                                        "$name (置信度: ${String.format("%.2f", confidence)})"
                                    }
                                }
                                if (labels.isNotEmpty()) {
                                    onLabelsDetected(labels)
                                }
                            }
                            .addOnCompleteListener { imageProxy.close() }
                    } else {
                        imageProxy.close()
                    }
                })
            }
            cameraProvider.unbindAll()
            cameraProvider.bindToLifecycle(lifecycleOwner, CameraSelector.DEFAULT_BACK_CAMERA, preview, imageAnalyzer)
        }, ctx.mainExecutor)
        previewView
    }, modifier = Modifier)
}

fun playMedia(context: Context, objectId: String) {
    // 假设资源命名为 object_物体ID.mp4 / object_物体ID.mp3
    val videoResId = context.resources.getIdentifier("object_${objectId}", "raw", context.packageName)
    val audioResId = context.resources.getIdentifier("object_${objectId}", "raw", context.packageName)
    if (videoResId != 0) {
        val exoPlayer = ExoPlayer.Builder(context).build()
        val videoUri = Uri.parse("android.resource://${context.packageName}/$videoResId")
        exoPlayer.setMediaItem(MediaItem.fromUri(videoUri))
        exoPlayer.prepare()
        exoPlayer.playWhenReady = true
    }
    if (audioResId != 0) {
        val mediaPlayer = MediaPlayer.create(context, audioResId)
        mediaPlayer.start()
    }
} 